package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.OrderAdapter;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Order;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class OrderActivity extends BaseActivity {
	private ListView mOrderLv;
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private List<Order> mOrders = new ArrayList<Order>();
	private OrderAdapter mAdapter;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private NormalDialog mNormalDialog;
	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;

		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				initData();
				break;
			case 1:
				int position = msg.arg1;
				int status = mOrders.get(position).getStatus();
				switch (status) {
				case 1:
					ToastShow.Show(getApplicationContext(), "申请售后接口尚未开通");
					break;
				case 2:
//					cancelOrder(position);
					confirm(position);
					break;
				case 8:
//					cancelOrder(position);
					confirm(position);
					break;
				default:
					break;
				}
				break;
			case 2:
				ToastShow.Show(getApplicationContext(), "撤销成功！");
				getAllOrders();
				break;
			default:
				break;
			}
		}
	};

	private void initData() {
		mOrders = DeviceManager.getInstance().getOrders();
		mAdapter = new OrderAdapter(getApplicationContext(), mOrders);
		mAdapter.setHandler(mHandler);
		mOrderLv.setAdapter(mAdapter);
	}

	private void confirm(final int p){
		mNormalDialog = new NormalDialog(OrderActivity.this);
		mNormalDialog
				.content("是否撤销该工单：工单" + mOrders.get(p).getId() + "？")
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				cancelOrder(p);
			}
		});
	}
	
	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_order1;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mOrderLv = $(R.id.order_lv);
		mStatusBar = $(R.id.tv_statusBar_mian);
		boolVersion();
		mBackL.setOnClickListener(this);
		getAllOrders();
	}

	public void getAllOrders() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_ORDER_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(),
						"token", ""));
				Log.d("test", " get all obj = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "get all order =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							DeviceManager.getInstance().clearOrder();
							DeviceManager.getInstance().getCurrentOrder().setStatus(0);
							JSONArray ja = jsonObject.getJSONArray("data");
							for (int i = 0; i < ja.length(); i++) {
								JSONObject jo = ja.getJSONObject(i);
								String id = jo.getString("id");
								String publishUserId = jo
										.getString("publishUserId");
								String publishUserName = jo
										.getString("publishUserName");
								String publishUserPhone = jo
										.getString("publishUserPhone");
								int createTime = jo.getInt("createTime");
								long installerTime = jo.getLong("installerTime");
								String explain = jo.optString("explain");
								int status = jo.getInt("status");
								double score = jo.getDouble("score");
								String shopOrderNumber = jo.optString("shopOrderNumber");
								String region = jo.getString("region");
								String address = jo.getString("address");
								Order order = new Order(id, publishUserId,
										publishUserName, publishUserPhone,
										createTime, installerTime, explain,
										status, score, region, address,shopOrderNumber);
								DeviceManager.getInstance().addOrder(order);
								if((status==8||status==2)&&score==0){
									DeviceManager.getInstance().setCurrentOrder(order);
								}
							}
							
							Message msg = Message.obtain();
							msg.what = 0;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getApplicationContext(),
									"您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getApplicationContext(),
									LoginActivity.class));
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}
	
	private void cancelOrder(int p){
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				ToastShow.Show(getApplicationContext(), "没有网络");
				return;
			}
			RequestParams params = new RequestParams(HttpURL.REVOKE_ORDER_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("handlType", "2");
				obj.put("id", mOrders.get(p).getId());
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(),
						"token", ""));
				obj.put("score", "0");
				Log.d("test", " cancel order = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "cancel order =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							Message msg = Message.obtain();
							msg.what = 2;
							mHandler.sendMessage(msg);
						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getApplicationContext(),
									"您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getApplicationContext(),
									LoginActivity.class));
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

}
